package mb.model;

import java.awt.Color;
import java.awt.Point;
import java.awt.Component;  // +
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;

public class Diagram extends JPanel implements MouseListener {

  public static final Color DIAGRAM_COLOR = Color.WHITE;  // +

  public Diagram() {
    super();
    this.addMouseListener(this);
    this.setBackground(DIAGRAM_COLOR);  // &
    this.setLayout(null);
  }

  private void addNewBox(Point aPoint) {
    Box newBox = new Box();
    newBox.setLocation(aPoint);
    newBox.addMouseListener(this);
    this.add(newBox);
    this.repaint();
  }

  // {+
  public void selectAllBoxes() {
    Component[] components = this.getComponents();
    Box box;
    for (int i = 0; i < components.length; i++) {
      if (components[i] instanceof Box) {
        box = (Box) components[i];
        box.setSelected(true);
      }
    }
  }

  public void deSelectAllBoxes() {
    Component[] components = this.getComponents();
    Box box;
    for (int i = 0; i < components.length; i++) {
      if (components[i] instanceof Box) {
        box = (Box) components[i];
        box.setSelected(false);
      }
    }
  }

  public void hideSelectedBoxes() {
    Component[] components = this.getComponents();
    Box box;
    for (int i = 0; i < components.length; i++) {
      if (components[i] instanceof Box) {
        box = (Box) components[i];
        if (box.isSelected()) {
          box.setVisible(false);
        }
      }
    }
  }

  public void showSelectedBoxes() {
    Component[] components = this.getComponents();
    Box box;
    for (int i = 0; i < components.length; i++) {
      if (components[i] instanceof Box) {
        box = (Box) components[i];
        if (box.isSelected()) {
          box.setVisible(true);
        }
      }
    }
  }
  // +}

  public void mousePressed(MouseEvent e) {
    if (e.getSource() == this) {
      this.addNewBox(e.getPoint());
    }
    else if (e.getSource() instanceof Box) {
      Box clickedBox = (Box) (e.getSource());
      clickedBox.setSelected(!(clickedBox.isSelected()) );
    }
  }

  public void mouseClicked(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}
  public void mouseEntered(MouseEvent e) {}
  public void mouseExited(MouseEvent e) {}
  
}